<?php

namespace Admin\Logic;

use Admin\Common\Category;

class FoodCateLogic
{
    public static function getAll()
    {
        try {
            $data = D('FoodCate')->order('order_sort asc')->select();
            return $data;
        } catch (\Exception $e) {
            return false;
        }
    }

    public static function getShowCate()
    {

        try {
            $data = D('FoodCate')->where(['is_show'=>1])->order('order_sort asc')->select();
            return $data;
        } catch (\Exception $e) {
            return false;
        }

    }

    /**
     * 处理添加数据信息
     * @Author    zhouyao
     * @DateTime  2017-11-20
     * @version   [version]
     * @param     [array] 表单数据
     * @return    [type]
     */
    public static function create($param)
    {
        try {
            $foodCate = D('FoodCate');

            if (!$foodCate->create($param)) { //创建数据对象
                return ['code' => 1, 'msg' => $foodCate->getError()];
            }

            $id = $foodCate->add();
            return ['code' => 0, 'msg' => $id];
        } catch (\Exception $e) {
            return false;
        }
    }


    /**
     * 执行删除分类操作
     * @param $id
     * @return string
     */
    public static function delete($id)
    {
        // 判断是否有子分类
        $children = Category::isHaveChildren($id,'FoodCate');
        if($children){
            // 存在子分类
            return json_encode(['code'=>0,'errorMsg'=>'请先删除其子分类']);
        }

        // 判断此分类下面是否有商品
        $goods = Category::isHaveGoods($id,'Food');


        if($goods == false){
            return json_encode(['code'=>0,'errorMsg'=>'服务器找不到了']);
        } elseif ($goods['code'] == 1){
            // 存在商品
            return json_encode(['code'=>0,'errorMsg'=>'请先删除分类下的菜谱']);
        }



        try {
            $update = D('FoodCate')->where('id='.$id)->delete();
            return json_encode(['code'=>1]);
        } catch (\Exception $e) {
            return json_encode(['code'=>0,'errorMsg'=>'删除失败，请重试']);
        }
    }

    /**
     * 修改分类操作
     * @param $data
     * @return bool
     */
    public static function update($data)
    {
        try {
            $update = D('FoodCate')->save($data);
            return $update;
        } catch (\Exception $e) {
            return false;
        }
    }



}